package logic

import (
	"context"
	"encoding/json"
	"fmt"
	"taobao_svc/models/cache"
	"taobao_svc/models/mysql"
	"time"

	"taobao_svc/internal/svc"
	"taobao_svc/taobao"

	"github.com/zeromicro/go-zero/core/logx"
)

type ProductShowLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewProductShowLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ProductShowLogic {
	return &ProductShowLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 商品详情
func (l *ProductShowLogic) ProductShow(in *taobao.ProductShowRequest) (*taobao.ProductShowResponse, error) {
	// todo: add your logic here and delete this line

	var product mysql.Product
	mysql.DB.Debug().Where("id = ?", in.Id).Find(&product)

	key := fmt.Sprintf("product_show_")
	result, _ := cache.Rdb.Get(l.ctx, key).Result()
	if result != "" {
		fmt.Println("使用缓存")
		json.Unmarshal([]byte(result), &product)
	} else {
		marshal, _ := json.Marshal(product)
		cache.Rdb.Set(l.ctx, key, marshal, time.Minute*3)
	}

	return &taobao.ProductShowResponse{
		Name:        product.Name,
		CategoryId:  int64(product.CategoryID),
		Description: product.Description,
		Price:       float32(product.Price),
		Stock:       int64(product.Stock),
		Status:      int64(product.Status),
	}, nil
}
